//
//  LoginViewController.m
//  suRead
//
//  Created by 李 诗洋 on 15/11/9.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "LoginViewController.h"

#import "ServiceNews.h"
#import "ServiceUserNew.h"
#import "Masonry.h"
#import "ShareService.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "AccountManager.h"
#import "COLocationManager.h"
#import "NewsWebViewController.h"

@interface LoginViewController ()<UIGestureRecognizerDelegate>

@property (strong, nonatomic) IBOutlet UINavigationItem *loginNavigationItem;
@property (strong, nonatomic) IBOutlet UIView *loginAccountView;
@property (strong, nonatomic) IBOutlet UIView *loginPwdView;
@property (strong, nonatomic) IBOutlet UITextField *loginAccountText;
@property (strong, nonatomic) IBOutlet UITextField *loginPwdText;

@property (strong,nonatomic) IBOutlet UIButton *linkReg;

@property (strong,nonatomic) COLocationManager *locationManager;
@end

@implementation LoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationManager = [COLocationManager new];

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // enable slide-back
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }

    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor colorWithRed:238/255.0f green:238/255.0f blue:238/255.0f alpha:1.0f];
    
    
//    NSMutableAttributedString *reglinktitle = [[NSMutableAttributedString alloc] initWithString:@"注册看楚天账号"];
//    NSRange titleRange = {0,[reglinktitle length]};
//    [reglinktitle addAttribute: NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
//
//    [reglinktitle addAttribute:NSForegroundColorAttributeName
//                         value:[UIColor redColor]  range:titleRange];
//
//    [self.linkReg setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//    [self.linkReg setAttributedTitle:reglinktitle forState:UIControlStateNormal];
//
//    self.loginAccountView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
//    self.loginAccountView.layer.borderWidth = 1.0f;
    

//    self.loginPwdView.layer.borderColor = [UIColor colorWithRed:233/255.0f green:233/255.0f blue:233/255.0f alpha:1.0f].CGColor;
//    self.loginPwdView.layer.borderWidth = 1.0f;
    
}

- (IBAction)actionSubmit:(id)sender {
    if([self.loginAccountText.text isEqualToString:@""]){
        return [theAppDelegate alert:@"手机号不能为空!"];
    }
    if (![self validateUserName:self.loginAccountText.text]) {
        return [theAppDelegate alert:@"手机号格式不正确!"];
    }
    if([self.loginPwdText.text isEqualToString:@""]){
        return [theAppDelegate alert:@"密码不能为空!"];
    }
    if (![self validatePassword:self.loginPwdText.text]) {
        return [theAppDelegate alert:@"密码格式不正确!"];
    }
    
    __weak typeof(self) weakSelf = self;
    
    [self showHUDProgress:nil];
    [ServiceUserNew doLogin:self.loginAccountText.text password:self.loginPwdText.text success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        [weakSelf removeHUDProgress];
        [weakSelf showHUDText:message];
        
        AccountManager *manager = [AccountManager sharedAccountManager];
        manager.f_isLogined = YES;
        manager.f_authCode = [responseObject objectForKey:@"token"];
        manager.f_nickname = [responseObject objectForKey:@"nick_name"];
        manager.f_phone_num = [responseObject objectForKey:@"phone"];
        manager.f_uid = [responseObject objectForKey:@"member_id"];
        manager.f_user_img = [responseObject objectForKey:@"cover"];
        
        // 登录成功，增加积分
        [ServiceUserNew doAddScore:AddScoreType_Login
                           success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {}
                           failure:^(NSString * _Nonnull message) {}];
        
//        [weakSelf.locationManager location:^(CLLocationCoordinate2D location) {
//            // 记录登录日志
//            [ServiceUserNew doLoginLog:weakSelf.loginAccountText.text location:location success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
//                
//            } failure:^(NSString * _Nonnull message) {
//                
//            }];
//        }];
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
        [weakSelf dismissViewControllerAnimated:YES completion:nil];

        if ([_delegate respondsToSelector:@selector(refershUserInfo)]) { // 如果协议响应了sendValue:方法
            [_delegate refershUserInfo]; // 通知执行协议方法
        }
        
    } failure:^(NSString * _Nonnull message) {
        [weakSelf removeHUDProgress];
        [weakSelf showHUDText:message];
    }];
    
}

- (IBAction)secure:(id)sender {
    NewsWebViewController *controller = [NewsWebViewController new];
    controller.hidesBottomBarWhenPushed = YES;
    controller.urlString = @"http://www.ctdsb.net/index.php?m=content&c=index&a=show&catid=27&id=3953";
    controller.hasShare = NO;
    [self showViewController:controller sender:nil];
}

//用户名
- (BOOL) validateUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}


//密码
- (BOOL) validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)goBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return YES;
}

- (IBAction)buttonQQOnclick:(id)sender
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"QQ uid: %@", resp.uid);
            NSLog(@"QQ openid: %@", resp.openid);
            NSLog(@"QQ unionid: %@", resp.unionId);
            NSLog(@"QQ accessToken: %@", resp.accessToken);
            NSLog(@"QQ expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"QQ name: %@", resp.name);
            NSLog(@"QQ iconurl: %@", resp.iconurl);
            NSLog(@"QQ gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"QQ originalResponse: %@", resp.originalResponse);
            
//            [ServiceUser doThirdPartLogin:resp.openid
//                                 nickname:resp.name
//                                   typeid:@"1"
//                                  imgpath:resp.iconurl
//                                  success:^(id responseObject, NSString *message) {
//                                      [self showHUDText:message];
//                                      [self.navigationController popViewControllerAnimated:YES];
//                                      [self dismissViewControllerAnimated:YES completion:nil];
//                                      if ([_delegate respondsToSelector:@selector(refershUserInfo)]) { // 如果协议响应了sendValue:方法
//                                          [_delegate refershUserInfo]; // 通知执行协议方法
//                                      }
//                                  } failure:^(NSString *message) {
//                                      [self showHUDText:message];
//                                  }];
        }
    }];
}

- (IBAction)buttonWechatOnclick:(id)sender
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat unionid: %@", resp.unionId);
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            NSLog(@"Wechat iconurl: %@", resp.iconurl);
            NSLog(@"Wechat gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
            
//            [ServiceUser doThirdPartLogin:resp.openid
//                                 nickname:resp.name
//                                   typeid:@"3"
//                                  imgpath:resp.iconurl
//                                  success:^(id responseObject, NSString *message) {
//                                      [self showHUDText:message];
//                                      [self.navigationController popViewControllerAnimated:YES];
//                                      [self dismissViewControllerAnimated:YES completion:nil];
//                                      if ([_delegate respondsToSelector:@selector(refershUserInfo)]) { // 如果协议响应了sendValue:方法
//                                          [_delegate refershUserInfo]; // 通知执行协议方法
//                                      }
//                                  } failure:^(NSString *message) {
//                                      [self showHUDText:message];
//                                  }];
        }
    }];
}

- (IBAction)buttonSinaOnclick:(id)sender
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_Sina currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            // 授权信息
            NSLog(@"Sina uid: %@", resp.uid);
            NSLog(@"Sina accessToken: %@", resp.accessToken);
            NSLog(@"Sina refreshToken: %@", resp.refreshToken);
            NSLog(@"Sina expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Sina name: %@", resp.name);
            NSLog(@"Sina iconurl: %@", resp.iconurl);
            NSLog(@"Sina gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"Sina originalResponse: %@", resp.originalResponse);
            
//            [ServiceUser doThirdPartLogin:resp.uid
//                                 nickname:resp.name
//                                   typeid:@"2"
//                                  imgpath:resp.iconurl
//                                  success:^(id responseObject, NSString *message) {
//                                      [self showHUDText:message];
//                                      [self.navigationController popViewControllerAnimated:YES];
//                                      [self dismissViewControllerAnimated:YES completion:nil];
//                                      if ([_delegate respondsToSelector:@selector(refershUserInfo)]) { // 如果协议响应了sendValue:方法
//                                          [_delegate refershUserInfo]; // 通知执行协议方法
//                                      }
//                                  } failure:^(NSString *message) {
//                                      [self showHUDText:message];
//                                  }];
        }
    }];
}

@end
